package apis

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"gorm.io/gorm/clause"
	"net/http"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/teacher/service"
	"tuowei.com/app/teacher/service/dto"
	"tuowei.com/app/teacher/service/response"
)

type Students struct {
	api.Api
	base
}

func (stu Students) GetStudentDetail(ctx *gin.Context) {
	req := dto.GetStudentDetailRequest{}
	s := service.StudentsService{}
	teacherInfo := stu.GetTeacherInfo(ctx)
	err := stu.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	obj := new(models.SysStudent)
	err = s.GetStudentsDetail(&req, obj)
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	rsp := &response.GetStudentDetail{}
	rsp.MakeResponse(obj)

	if obj.EnrollmentTeacherId != teacherInfo.SysUser.UserId &&
		obj.TeachRecommender != teacherInfo.SysUser.UserId {
		stu.Error(http.StatusInternalServerError, nil, "无权查看不属于自己的学生")
		return
	}
	stu.OK(rsp, "success")
}

// 获取分班/未分班学生列表
func (stu Students) GetStudentsList(ctx *gin.Context) {
	s := service.StudentsService{}
	req := dto.GetStudentsListRequest{}
	err := stu.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Query).
		MakeService(&s.Service).Errors
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	teacherInfo := stu.GetTeacherInfo(ctx)
	if teacherInfo == nil {
		stu.Error(http.StatusUnauthorized, errors.New("不应该啊"), "请重新登陆")
		return
	}
	lists := make([]models.SysStudent, 0)
	var count int64
	err = s.GetStudentsList(&lists, &count, teacherInfo.SysUser.UserId, req)
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	rsp := make([]response.StudentsLists, 0)
	for _, v := range lists {
		rsp = append(rsp, response.StudentsLists{
			Id:       v.Id,
			Name:     v.Name,
			Phone:    v.Phone,
			UserType: v.UserType,
		})
	}
	stu.PageOK(rsp, int(count), req.GetPageIndex(), req.GetPageSize(), "success")
}

func (stu Students) SubmitCommunication(ctx *gin.Context) {
	teacherInfo := stu.GetTeacherInfo(ctx)
	if teacherInfo == nil {
		stu.Error(http.StatusUnauthorized, errors.New("不应该啊"), "请重新登陆")
		return
	}
	s := service.StudentsService{}
	req := dto.SubmitCommunicationRequest{}
	err := stu.MakeContext(ctx).MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).Errors
	if err != nil {
		stu.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	// 检测这个订单对应的老师到底是不是你，别瞎po接口
	model := new(models.OfflineOrder)
	model.Id = req.OrderId
	err = s.GetOfflineOrderDetailById(model)
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	if model.Status != 2 {
		stu.Error(http.StatusInternalServerError, err, "订单状态不是待跟进状态!")
		return
	}
	if model.Customer == nil {
		stu.Error(http.StatusInternalServerError, err, "对应的学生不存在")
		return
	}
	if model.Customer.EnrollmentTeacherId != teacherInfo.SysUser.UserId {
		stu.Error(http.StatusInternalServerError, err, "此订单不属于你!")
		return
	}
	req.Generate(model)
	db := stu.Orm.Omit(clause.Associations).Save(model)
	if db.Error != nil {
		stu.Error(http.StatusInternalServerError, err, db.Error.Error())
		return
	}
	if db.RowsAffected == 0 {
		stu.Error(http.StatusInternalServerError, errors.New("无权更新该数据"), "无权更新该数据")
		return
	}
	stu.OK(nil, "success")
}

func (stu Students) GetOnlineOrderHistoryList(ctx *gin.Context) {
	req := dto.StudentOrderHistoryListRequest{}
	s := service.StudentsService{}
	err := stu.MakeContext(ctx).MakeOrm().MakeService(&s.Service).Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		stu.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	list := make([]models.OnlineOrder, 0)
	db, err := stu.GetOrm()
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	err = (models.OnlineOrder{}).GetStudentList(db, &list, req.Id, req.GetPageIndex(), req.GetPageSize())
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	rsp := make([]response.OnlineOrderHistoryListResponse, 0)
	for k := range list {
		arr := make([]response.Course, len(list[k].Course))
		for kk, vv := range list[k].Course {
			arr[kk] = response.Course{
				CourseId:     vv.CourseId,
				Name:         vv.Name,
				Introduction: vv.Introduction,
			}
		}
		rsp = append(rsp, response.OnlineOrderHistoryListResponse{
			Subject: list[k].Subject,
			Courses: arr,
			Price:   list[k].Price,
			Status:  list[k].Status,
		})
	}
	stu.OK(rsp, "success")
}

func (stu Students) GetOfflineOrderHistoryList(ctx *gin.Context) {
	req := dto.StudentOrderHistoryListRequest{}
	s := service.StudentsService{}
	err := stu.MakeContext(ctx).MakeOrm().MakeService(&s.Service).Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		stu.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	list := make([]models.OfflineOrder, 0)
	db, err := stu.GetOrm()
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	err = (models.OfflineOrder{}).GetStudentList(db, &list, req.Id, req.GetPageIndex(), req.GetPageSize())
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	rsp := make([]response.OnlineOrderHistoryListResponse, 0)
	for k := range list {
		arr := make([]response.Course, len(list[k].Course))
		for kk, vv := range list[k].Course {
			arr[kk] = response.Course{
				CourseId:     vv.CourseId,
				Name:         vv.Name,
				Introduction: vv.Introduction,
			}
		}
		rsp = append(rsp, response.OnlineOrderHistoryListResponse{
			Subject: list[k].Subject,
			Courses: arr,
			Price:   list[k].Price,
			Status:  list[k].Status,
		})
	}
	stu.OK(rsp, "success")
}

func (stu Students) DivisionStudent(ctx *gin.Context) {
	req := dto.DivisionStudentRequest{}
	s := service.StudentsService{}
	teacherInfo := stu.GetTeacherInfo(ctx)
	err := stu.MakeContext(ctx).
		MakeOrm().
		MakeService(&s.Service).
		Bind(&req, binding.JSON).
		Errors
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	lists, err := s.GetStudentByIds(req.Ids)
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	for _, s := range lists {
		if s.EnrollmentTeacherId != teacherInfo.SysUser.UserId {
			stu.Error(http.StatusInternalServerError, nil, "学员["+s.Name+"]的招生老师不是你")
			return
		}
	}
	err = s.DivisionStudent(&req)
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	stu.OK(nil, "success")
}

func (stu Students) GetClass(ctx *gin.Context) {
	s := service.StudentsService{}
	req := dto.GetClassRequest{}
	err := stu.MakeContext(ctx).MakeOrm().MakeService(&s.Service).Bind(&req, nil).Errors
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	classes := make([]models.SysClass, 0)
	err = s.GetClassByAreaId(&req, &classes)
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	rsp := make([]response.ClassResponse, len(classes))
	for k := range classes {
		rsp[k] = response.ClassResponse{
			Name: classes[k].Name,
			Id:   classes[k].Id,
		}
	}
	stu.OK(rsp, "success")
}

func (stu Students) GetCondition(ctx *gin.Context) {
	deptService := service.TeachingPointService{}
	err := stu.MakeContext(ctx).MakeOrm().MakeService(&deptService.Service).Errors
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	user := stu.GetTeacherInfo(ctx)
	// 获取部门
	areas := deptService.GetCondition(user.SysUser.UserId)
	labels := []string{"线上", "线下"}
	statesArr := make([]models.SysStudentState, 0)
	stu.Orm.Find(&statesArr)
	stateMap := make(map[int]string)
	for _, v := range statesArr {
		stateMap[v.Id] = v.Name
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": map[string]interface{}{
			"areas":  areas,
			"labels": labels,
			"states": statesArr,
		},
	})
}

func (stu Students) List(ctx *gin.Context) {
	s := service.StudentsService{}
	req := dto.GetManageStudentsListsRequest{}
	err := stu.MakeContext(ctx).MakeOrm().MakeService(&s.Service).
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).Errors
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	teacher := stu.GetTeacherInfo(ctx)
	list, count, err := s.GetManageStudentsLists(teacher.SysUser.UserId, &req)
	if err != nil {
		stu.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	for k, v := range list {
		if v.Cover == "" {
			if v.QqStudents != nil {
				list[k].Cover = v.QqStudents.FigureurlQq1
				continue
			}
			if v.WxStudents != nil {
				list[k].Cover = v.WxStudents.Avatar
			}
		}
	}
	stu.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "success")
}
